#include <ArduinoJson.h>
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <string.h>
#include <TimeLib.h>
#include "Setting.h"
#include "JsonConf.h"
#include <ESPAsyncWebServer.h>
#include "SSD1306Wire.h" // legacy include: `#include "SSD1306.h"`
#include "OLEDDisplayUi.h"
#include "cnFont.h"


WiFiClient wifiClient;
AsyncWebServer server(80);
SSD1306Wire display(0x3c, SDA, SCL);
OLEDDisplayUi ui ( &display );

void clockOverlay(OLEDDisplay *display, OLEDDisplayUiState* state) {

}
OverlayCallback overlays[] = { clockOverlay };
int overlaysCount = 1;

void logger(String mess) {
  Serial.println(mess);
}
double _y = 0;
// 界面顺序
FrameCallback frames[] = {drawWatherTime,  watherToday1, watherToday2,  watherTomorrowAndAfterTomorrow, bigClock};
int frameCount = 5;

void setup() {
  Serial.begin(115200); // 打开串口
  delay(1000);
  ui.setTargetFPS(60);
  ui.setActiveSymbol(activeSymbol);
  ui.setInactiveSymbol(inactiveSymbol);
  ui.setIndicatorPosition(TOP);
  ui.setIndicatorDirection(LEFT_RIGHT);
  //ANIMATION_inactiveSymbol
  ui.setActiveSymbol(animation_inactive_symbol);
  ui.setFrameAnimation(SLIDE_LEFT);
  ui.setFrames(frames, frameCount);
  ui.setOverlays(overlays, overlaysCount);
  // ui.disableAutoTransition();
  ui.init();
  display.init();
  display.flipScreenVertically();
  welcome();
  display.display();
  // 读取配置数据
  if (SPIFFS.begin()) {
    showFSInfo();
  }
  else
  {
    logger("ERROR :: SPIFFS 文件系统获取失败");
    return;
  }

  if (loadJsonConf(CONF_FILE_NAME))
  {
    UserConf conf = getUserConf();
    logger(conf.sid);
    logger(conf.pass);
    WiFi.begin(conf.sid, conf.pass);
  }
  else
  {
    startApServer();
    return;
  }

  // 判断密码存在进行连接
  //  WiFi.begin(WIFI_SID, WIFI_PASS);
  int i = 0;
  while (WiFi.status() != WL_CONNECTED)
  {
    i++;
    delay(500);
    if (i > 20) { //10秒后如果还是连接不上，就判定为连接超时
      break;
    }
  }

  if (WiFi.status() == WL_CONNECTED)
  {
    UserConf conf = getUserConf();
    getTimeNow( );
    getWatherNow(conf.wather_key, conf.localation);
    getDAily(conf.wather_key, conf.localation);


  }
  else {
    startApServer();
    return ;
  }

}

long interval = 60000;
unsigned long previousMillis = 0;
unsigned long previousMillis2 = 0;

void loop() {
  if (WiFi.status() == WL_CONNECTED)
  {
    ui.update();

    unsigned long currentMillis = millis();
    if (currentMillis - previousMillis >= interval * 20)
    {
      previousMillis = currentMillis;
      UserConf conf = getUserConf();
      getTimeNow( );
      getWatherNow(conf.wather_key, conf.localation);
    }

    if (currentMillis - previousMillis2 >= interval * 360)
    {
      previousMillis2 = currentMillis;
      UserConf conf = getUserConf();
      //      getLife(conf.wather_key, conf.localation);
      getDAily(conf.wather_key, conf.localation);
    }
  }
}
